package com.hlc.helloWord.common.aspect;

import com.alibaba.fastjson.JSON;
import org.apache.log4j.Logger;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by helinchong on 2017/12/19.
 */
@Aspect
//@Component
public class LogAspect {

    private Logger logger = Logger.getLogger(LogAspect.class);

    @Around("execution(* com.hlc.helloWord..controller..*.*(..))")
    public Object logOut(ProceedingJoinPoint joinPoint) throws Throwable {
        StringBuffer info = new StringBuffer();
        Object obj = null;

            ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = servletRequestAttributes.getRequest();
            info.append("request : {");
            info.append("getRequestURL : " + request.getRequestURL());
            info.append(",getMethod : " + request.getMethod());
            info.append(",CharacterEncoding : " + request.getCharacterEncoding());
            info.append(",ip : " + request.getRemoteHost());
            //获取请求参数
            Object[] paraments = joinPoint.getArgs();
            if (paraments != null && paraments.length > 0) {
                info.append(",parament : ");
                info.append(JSON.toJSONString(paraments));
            }
            info.append("}");

            // 执行目标组件的方法


            obj = joinPoint.proceed();
            //再执行方法之后执行官一些操作

            info.append("\nresponse : ");
            info.append(JSON.toJSONString(obj));
            logger.info(info);

        return obj;
    }
}
